//
//  LKHomeViewController.m
//  LKIntelligentVideoProject
//
//  Created by she1323 on 2018/9/20.
//  Copyright © 2018年 she1323. All rights reserved.
//

#import "LKHomeViewController.h"
#import "AppDelegate.h"
#import <LBXScanViewStyle.h>
#import "LKLockScanViewController.h"
#import "LKMapViewController.h"
#import "LKHomeBottomListCell.h"
#import "LKHomeTopCell.h"
#import <YWVideoPlayer/YWMediaPlayerView.h>
#import "LKMonitorVideoPlayerViewController.h"
#import "LKAddressPickerView.h"
#import "LKPickerAreaModel.h"
#import "LKMapBottomListCell.h"
#import <MJRefresh.h>
#import "LKSearchBar.h"
#define BMKAppkey @"Xs8oK7p5KvjwoCLmU8d1GfwErmCiZ5Ru"


@interface LKHomeViewController ()<UITableViewDelegate,UITableViewDataSource,YWMediaPlayerViewDelegate,BMKLocationManagerDelegate,BMKLocationAuthDelegate,UISearchBarDelegate>


@property(nonatomic,strong)LKBaseTableview *tableView;

@property(nonatomic,strong)NSMutableArray *bottomlistArray;

@property (nonatomic, strong)YWMediaPlayerView  *mediaPlayerView;

@property(nonatomic,strong)UIView *playerView;

@property(nonatomic,strong)UIButton *localBtn;

@property(nonatomic,strong)BMKUserLocation *userLocation;

@property(nonatomic,strong) BMKLocationManager *locationManager;//定位管理类

@property(nonatomic,strong)NSMutableArray *caculationTimeArray;

@property(nonatomic,strong)UISegmentedControl *segmentControl;

@property(nonatomic,copy)NSString *regionId;

@property(nonatomic,assign)NSInteger selectedSeg;

@property(nonatomic,assign)BOOL isFirstReload;

@property(nonatomic,assign)NSInteger PageIndex;

@property(nonatomic,assign)NSInteger MaxResultCount;

@property(nonatomic,strong)LKSearchBar *mySearchBar;

@property(nonatomic,copy)NSString *unitAddr;
@end

@implementation LKHomeViewController



-(LKBaseTableview *)tableView{
    if (!_tableView) {
        _tableView = [LKBaseTableview setTableviewWithFrame:CGRectMake(0, NAVIGATION_BAR_HEIGHT + YWMinPlayerHeight + 55 + 50, WIDTH, HEIGHT - NAVIGATION_BAR_HEIGHT - TAB_BAR_HEIGHT - YWMinPlayerHeight - 55 - 50) style:UITableViewStyleGrouped registercellClasss:@[NSStringFromClass([LKHomeBottomListCell class]),NSStringFromClass([LKHomeTopCell class]),NSStringFromClass([LKMapBottomListCell class])]];
        _tableView.delegate = self;
        _tableView.dataSource = self;
        _tableView.separatorStyle = UITableViewCellSeparatorStyleSingleLine;
        [self.view addSubview:_tableView];
    }
    return _tableView;
}
//设置搜索框
-(void)setupSearchView{
    LKSearchBar *searchBar = [[LKSearchBar alloc] init];
    [self.view addSubview:searchBar];
    [searchBar mas_makeConstraints:^(MASConstraintMaker *make) {
        make.centerX.equalTo(self.view);
        make.height.mas_equalTo(30);
        make.top.equalTo(self.segmentControl.mas_bottom).offset(10);
        make.width.mas_equalTo(WIDTH );
    }];
    UIButton *cancel = [searchBar valueForKey:@"_cancelButton"];
    [cancel setTitle:@"取消" forState:UIControlStateNormal];
    [cancel setTitleColor:[UIColor blueColor] forState:UIControlStateNormal];
    //默认提示文字
    searchBar.placeholder = @"搜索";
    searchBar.delegate = self;
    self.mySearchBar = searchBar;
}
- (void)viewWillAppear:(BOOL)animated{
    [super viewWillAppear:animated];
    self.tabBarController.tabBar.hidden = NO;
    self.navigationItem.title = @"智能机房监控";
    //确保在该控制器即将出现的时候开启全屏模式
    ((AppDelegate *) [[UIApplication sharedApplication] delegate]).fullScreen = YES;
    
    UIButton *scanBtn = [UIButton buttonWithType:UIButtonTypeCustom];
    scanBtn.size = [UIImage imageNamed:@"saoyisao"].size;
    [scanBtn setImage:[UIImage imageNamed:@"saoyisao"] forState:UIControlStateNormal];
    [scanBtn setTitleColor:blueDefault forState:UIControlStateNormal];
    [scanBtn addTarget:self action:@selector(chooseErweima) forControlEvents:UIControlEventTouchUpInside];
    
    UIButton *mapEntranceBtn = [UIButton buttonWithType:UIButtonTypeCustom];
    mapEntranceBtn.size = [UIImage imageNamed:@"mapEntrance"].size;
    [mapEntranceBtn setImage:[UIImage imageNamed:@"mapEntrance"] forState:UIControlStateNormal];
    [mapEntranceBtn addTarget:self action:@selector(mapEntrance) forControlEvents:UIControlEventTouchUpInside];
    UIBarButtonItem *item1 = [[UIBarButtonItem alloc] initWithCustomView:mapEntranceBtn];
    UIBarButtonItem *item2 = [[UIBarButtonItem alloc] initWithCustomView:scanBtn];
    self.navigationItem.rightBarButtonItems = @[item1,item2];
<<<<<<< HEAD
    UIButton *localImageBtn = [UIButton buttonWithType:UIButtonTypeCustom];
    localImageBtn.size = [UIImage imageNamed:@"location"].size;
    [localImageBtn setImage:[UIImage imageNamed:@"location"] forState:UIControlStateNormal];
    self.selectedSeg = 0;
=======
>>>>>>> parent of 2e14138... 提交
    
    self.localBtn = [UIButton buttonWithType:UIButtonTypeCustom];
    [_localBtn setImage:[UIImage imageNamed:@"location"] forState:UIControlStateNormal];
    [_localBtn setTitleColor:[UIColor whiteColor] forState:UIControlStateNormal];
    _localBtn.titleLabel.font = [UIFont systemFontOfSize:12];
    _localBtn.titleLabel.textAlignment = NSTextAlignmentLeft;
    [_localBtn setTitle:@"上海市" forState:UIControlStateNormal];
    _localBtn.size = [NSString sizeWidthWidth:@"上海市" font:[UIFont systemFontOfSize:12] maxHeight:NAVIGATION_BAR_HEIGHT - STATUS_BAR_HEIGHT];
    [_localBtn addTarget:self action:@selector(localtionChoose) forControlEvents:UIControlEventTouchUpInside];
    self.navigationItem.leftBarButtonItem = [[UIBarButtonItem alloc] initWithCustomView:_localBtn];
<<<<<<< HEAD
    self.navigationItem.leftBarButtonItems = @[[[UIBarButtonItem alloc] initWithCustomView:localImageBtn],[[UIBarButtonItem alloc] initWithCustomView:_localBtn]];

//    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(showHouse) name:@"showHomeHouseActionNotice" object:nil];
//    [self showHouse];
}
/**
 接受是否显示机房的通知变化
 */
-(void)showHouse{
    self.segmentControl = nil;
    [self.segmentControl removeFromSuperview];
    for (UIView *subView in self.view.subviews ) {
        if ([subView isKindOfClass:[UISegmentedControl class]]) {
            [subView removeFromSuperview];
        }
    }
//    [self testVideoPlayWithFatherView:self.view];
    NSArray *items;
    if ([[NSUserDefaults standardUserDefaults] objectForKey:@"showHouse"] != nil) {
        BOOL showHouse = [[[NSUserDefaults standardUserDefaults] objectForKey:@"showHouse"] boolValue];
        if (showHouse) {
            items = @[@"监控",@"门禁",@"井盖",@"机房"];
        }else{
            items = @[@"监控",@"门禁",@"井盖"];
        }
    }else{
        items = @[@"监控",@"门禁",@"井盖",@"机房"];
    }
    [self.segmentControl removeSegmentAtIndex:0 animated:YES];
    self.segmentControl = [[UISegmentedControl alloc] initWithItems:items];
    self.selectedSeg = 0;
    [_segmentControl addTarget:self action:@selector(chooseDiffrentType:) forControlEvents:UIControlEventValueChanged];
    self.segmentControl.selectedSegmentIndex = 0;
    self.segmentControl.layer.borderColor = [UIColor lightGrayColor].CGColor;
    self.segmentControl.layer.borderWidth = 0.0000f;
    [self.segmentControl setTintColor:[UIColor lightGrayColor]];
    [self.segmentControl setDividerImage:[UIImage imageNamed:@""] forLeftSegmentState:UIControlStateNormal rightSegmentState:UIControlStateNormal barMetrics:UIBarMetricsDefault];
    [self.view addSubview:self.segmentControl];
    [self.segmentControl mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.equalTo(self.view.mas_left).offset(0);
        make.top.equalTo(self.playerView.mas_bottom).offset(5);
        make.height.mas_equalTo(50);
        make.right.equalTo(self.view.mas_right).offset(0);
    }];
    NSString *url;
    if (self.regionId) {
//        url = @"/unitInfo/server/app/selectByReginId";
        url = @"/unitInfo/server/app/getUnitInfoByRoleId";
    }else{
        url = @"/unitInfo/server/app/getUnitInfoByRoleId";
    }
    [self getDataListWithRegionId:self.regionId WithUrl:url WithType:self.selectedSeg];
}

/**
 地图定位的BMKLocationManager代理方法的实现
 
 */
-(void)BMKLocationManager:(BMKLocationManager *)manager didUpdateLocation:(BMKLocation *)location orError:(NSError *)error{
    if (error) {
        NSLog(@"locError:{%ld - %@};", (long)error.code, error.localizedDescription);
    }
    if (!location) {
        return;
    }
    if (!self.userLocation) {
        self.userLocation = [[BMKUserLocation alloc] init];
        self.userLocation.location = location.location;
        self.PageIndex = 1;
         [self getDataListWithRegionId:@"" WithUrl:@"/unitInfo/server/app/getUnitInfoByRoleId" WithType:self.selectedSeg];
         [self.locationManager stopUpdatingLocation];
        return;
    }
   
   
=======
    
    
>>>>>>> parent of 2e14138... 提交
}


/**
 地图的入口
 */
-(void)mapEntrance{
    LKMapViewController *mapVc = [[LKMapViewController alloc] init];
    mapVc.hidesBottomBarWhenPushed = YES;
    [self.navigationController pushViewController:mapVc animated:YES];
}

/**
 地理位置的定位选择
 */
-(void)localtionChoose{
    WS(weakSelf)
    LKAddressPickerView *picker = [[LKAddressPickerView alloc] initWithPicker];
    picker.cancelBtnAction = ^{
        weakSelf.regionId = nil;
        [weakSelf.localBtn setTitle:@"上海市" forState:UIControlStateNormal];
         weakSelf.localBtn.size = [NSString sizeWidthWidth:@"上海市" font:[UIFont systemFontOfSize:12] maxHeight:NAVIGATION_BAR_HEIGHT - STATUS_BAR_HEIGHT];
        weakSelf.PageIndex = 1;
        [weakSelf getDataListWithRegionId:self.regionId WithUrl:@"/unitInfo/server/app/getUnitInfoByRoleId" WithType:self.selectedSeg];
    };
    picker.confirmSelect = ^(NSArray *address) {
        SS(strongSelf)
//       NSString *currentProvince = address[0];
       NSString *currentCity = address[1];
        LKPickerAreaModel *areaModel = address[2];
<<<<<<< HEAD
        NSString *test = [NSString stringWithFormat:@"%@%@", currentCity, [NSString judegeIsNullAndTransform:areaModel.regionName]];
        [strongSelf.localBtn setTitle:test forState:UIControlStateNormal];
        strongSelf.localBtn.size = [NSString sizeWidthWidth:test font:[UIFont systemFontOfSize:12] maxHeight:NAVIGATION_BAR_HEIGHT - STATUS_BAR_HEIGHT];
        strongSelf.regionId = areaModel.Id;
        
//        [strongSelf getDataListWithRegionId:areaModel.Id WithUrl:@"/unitInfo/server/app/selectByReginId" WithType:3];
        strongSelf.PageIndex = 1;
        strongSelf.segmentControl.selectedSegmentIndex = 0;
        strongSelf.selectedSeg = 0;
        [strongSelf getDataListWithRegionId:areaModel.Id WithUrl:@"/unitInfo/server/app/getUnitInfoByRoleId" WithType:strongSelf.selectedSeg];
=======
        NSString *test = [NSString stringWithFormat:@"%@%@%@", currentProvince, currentCity, areaModel.regionName];
        [strongSelf.localBtn setTitle:test forState:UIControlStateNormal];
>>>>>>> parent of 2e14138... 提交
        NSLog(@"%@",test);
        NSLog(@"你要的ID=%@",areaModel.Id);
    };
    [picker show];
}
#pragma mark - lazyLoad

-(BMKLocationManager *)locationManager{
    if (!_locationManager) {
        _locationManager = [[BMKLocationManager alloc] init];
        _locationManager.coordinateType = BMKLocationCoordinateTypeBMK09LL;
        _locationManager.desiredAccuracy =  kCLLocationAccuracyNearestTenMeters;
        _locationManager.delegate = self;
    }
    return _locationManager;
}
//二维码的选择
-(void)chooseErweima{
    //设置扫码区域参数
    NSDictionary *param = @{@"code":@"sweep",@"roleId":[LKUserInforTool account].roleId};
    [[LKNetDataManager defaultManager] sendRequestMethod:HTTPMethodPOST serverUrl:ServerUrl apiPath:@"/role/server/app/queryAppPermissionsCode" parameters:param progress:^(NSProgress * _Nullable progress) {
        
    } success:^(BOOL isSuccess, id  _Nullable responseObject) {
        if ([responseObject[@"code"] isEqual:@"0000"]) {
            LBXScanViewStyle *style = [[LBXScanViewStyle alloc]init];
            style.centerUpOffset = 44;
            style.photoframeAngleStyle = LBXScanViewPhotoframeAngleStyle_Inner;
            style.photoframeLineW = 3;
            style.photoframeAngleW = 18;
            style.photoframeAngleH = 18;
            style.isNeedShowRetangle = NO;
            style.anmiationStyle = LBXScanViewAnimationStyle_LineMove;
            
            //qq里面的线条图片
            UIImage *imgLine = [UIImage imageNamed:@"CodeScan.bundle/qrcode_scan_light_green"];
            style.animationImage = imgLine;
            
            style.notRecoginitonArea = [UIColor colorWithRed:0 green:0 blue:0 alpha:0.6];
            LKLockScanViewController *vc = [[LKLockScanViewController alloc] init];
            vc.style = style;
            vc.isOpenInterestRect = YES;
            vc.libraryType = SLT_Native;
            vc.hidesBottomBarWhenPushed = YES;
            [self.navigationController pushViewController:vc animated:YES];
        }else{
            [SVProgressHUD showInfoWithStatus:responseObject[@"msg"]];
        }
    } failure:^(NSString * _Nullable errorMessage) {
        
    }];

}
- (void)viewWillDisappear:(BOOL)animated {
    [super viewWillDisappear:animated];
//    [[NSNotificationCenter defaultCenter] removeObserver:self];
    // 确保在该控制器即将消失的时候关闭全屏模式
    ((AppDelegate *) [[UIApplication sharedApplication] delegate]).fullScreen = NO;
}

- (void)viewDidLoad {
    [super viewDidLoad];
    self.unitAddr = @"";
    if (@available(iOS 11.0, *)) {
        [UIScrollView appearance].contentInsetAdjustmentBehavior = UIScrollViewContentInsetAdjustmentNever;//UIScrollView也适用
    } else {
        self.automaticallyAdjustsScrollViewInsets = NO;
    }
    self.view.backgroundColor = [UIColor whiteColor];
    self.PageIndex = 1;
    self.playerView = [[UIView alloc] initWithFrame:CGRectMake(0, NAVIGATION_BAR_HEIGHT, YWSCREEN_WIDTH, YWMinPlayerHeight)];
    self.playerView.backgroundColor = [UIColor grayColor];
    self.isFirstReload = YES;
    [self.view addSubview:self.playerView];
    NSArray *items;
    if ([[NSUserDefaults standardUserDefaults] objectForKey:@"showHouse"] != nil) {
        BOOL showHouse = [[[NSUserDefaults standardUserDefaults] objectForKey:@"showHouse"] boolValue];
        if (showHouse) {
            items = @[@"监控",@"门禁",@"井盖",@"机房"];
        }else{
            items = @[@"监控",@"门禁",@"井盖"];
        }
    }else{
        items = @[@"监控",@"门禁",@"井盖",@"机房"];
    }
    self.segmentControl = [[UISegmentedControl alloc] initWithItems:items];
    self.selectedSeg = 3;
    [_segmentControl addTarget:self action:@selector(chooseDiffrentType:) forControlEvents:UIControlEventValueChanged];
    self.segmentControl.selectedSegmentIndex = 0;
    self.segmentControl.layer.borderColor = [UIColor lightGrayColor].CGColor;
    self.segmentControl.layer.borderWidth = 0.0000f;
    [self.segmentControl setTintColor:[UIColor lightGrayColor]];
    [self.segmentControl setDividerImage:[UIImage imageNamed:@""] forLeftSegmentState:UIControlStateNormal rightSegmentState:UIControlStateNormal barMetrics:UIBarMetricsDefault];
    [self.view addSubview:self.segmentControl];
    [self.segmentControl mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.equalTo(self.view.mas_left).offset(0);
        make.top.equalTo(self.playerView.mas_bottom).offset(5);
        make.height.mas_equalTo(50);
        make.right.equalTo(self.view.mas_right).offset(0);
    }];
    [self setupSearchView];
    //启动LocationService
    [[BMKLocationAuth sharedInstance] checkPermisionWithKey:BMKAppkey authDelegate:self];
    [self.locationManager startUpdatingLocation];
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(showHouse) name:@"showHomeHouseActionNotice" object:nil];
    self.tableView.mj_header = [MJRefreshNormalHeader headerWithRefreshingTarget:self refreshingAction:@selector(headerReloadData)];
    self.tableView.mj_footer = [MJRefreshAutoNormalFooter footerWithRefreshingTarget:self refreshingAction:@selector(footerReloadData)];
}
/**
 头部下拉刷新
 */
-(void)headerReloadData{
    self.PageIndex = 1;
    NSString *url;
    if (self.regionId) {
//        url = @"/unitInfo/server/app/selectByReginId";
        url = @"/unitInfo/server/app/getUnitInfoByRoleId";
    }else{
        url = @"/unitInfo/server/app/getUnitInfoByRoleId";
    }
    [self getDataListWithRegionId:self.regionId WithUrl:url WithType:self.selectedSeg];
}

/**
 尾部上拉加载更多
 */
-(void)footerReloadData{
    self.PageIndex++;
    NSString *url;
    if (self.regionId) {
//        url = @"/unitInfo/server/app/selectByReginId";
        url = @"/unitInfo/server/app/getUnitInfoByRoleId";
    }else{
        url = @"/unitInfo/server/app/getUnitInfoByRoleId";
    }
    [self getDataListWithRegionId:self.regionId WithUrl:url WithType:self.selectedSeg];
}
/**
 获取设备列表数据
 */
-(void)getDataListWithRegionId:(NSString *)regionId WithUrl:(NSString *)url WithType:(NSInteger) type{
    /**
     设备类型
     1.井盖
     2.门禁
     3.监控
     4.机房
     */
    NSDictionary *param;
    NSString *unitType;
    NSString *currentPage = [NSString stringWithFormat:@"%ld",self.PageIndex];
    NSString *limit = [NSString stringWithFormat:@"%d",10];
    if (type == 0) {
        unitType = @"3";
    }else if (type == 1){
        unitType = @"2";
    }else if (type == 2){
        unitType = @"1";
    }else{
        unitType = @"4";
    }
//    NSString *unitType = [NSString stringWithFormat:@"%ld",type];
    if (self.isFirstReload) {
        self.isFirstReload = NO;
    }else{
       [SVProgressHUD showWithStatus:@"数据加载中..."];
       [SVProgressHUD setDefaultMaskType:SVProgressHUDMaskTypeClear];
    }
    if (!self.regionId) {
            param = @{@"roleId":[LKUserInforTool account].roleId,@"userUuid":[LKUserInforTool account].userUuid,@"page":currentPage,@"limit":limit,@"callSource":@"1",@"unitType":unitType,@"showPlace":@"2",@"unitAddr":self.unitAddr};
    }else{
        if ([self.localBtn.titleLabel.text containsString:@"区全部"]) {
            //        param = [NSDictionary dictionaryWithObjectsAndKeys:[LKUserInforTool account].userUuid,@"userUuid",regionId,@"reginId", nil];
            param = @{@"roleId":[LKUserInforTool account].roleId,@"userUuid":[LKUserInforTool account].userUuid,@"page":currentPage,@"limit":limit,@"callSource":@"1",@"unitType":unitType,@"showPlace":@"2",@"unitAddr":self.unitAddr,@"prentId":self.regionId};
        }else{
            param = @{@"roleId":[LKUserInforTool account].roleId,@"userUuid":[LKUserInforTool account].userUuid,@"page":currentPage,@"limit":limit,@"callSource":@"1",@"unitType":unitType,@"showPlace":@"2",@"unitAddr":self.unitAddr,@"reginId":self.regionId};
        }
    }

    [[LKNetDataManager defaultManager] sendRequestMethod:HTTPMethodPOST serverUrl:ServerUrl apiPath:url parameters:param progress:^(NSProgress * _Nullable progress) {
        
    } success:^(BOOL isSuccess, id  _Nullable responseObject) {
        [SVProgressHUD dismiss];
        [self.tableView.mj_header endRefreshing];
        [self.tableView.mj_footer endRefreshing];
        if (self.PageIndex == 1) {
            [self.bottomlistArray removeAllObjects];
        }
        if ([responseObject[@"data"] isEqual:[NSNull null]]) {
            [self.tableView reloadData];
            return ;
        }

        NSArray *arra = responseObject[@"data"];
        for (NSDictionary *dic in arra) {
            @autoreleasepool{
                LKMapPointModel *model = [LKMapPointModel modelWithDictionary:dic];
                if ([unitType isEqual:model.unitType]) {
                    model.curentPt = self.userLocation.location.coordinate;
                    BMKMapPoint point1 = BMKMapPointForCoordinate(self.userLocation.location.coordinate);
                    BMKMapPoint point2 = BMKMapPointForCoordinate(CLLocationCoordinate2DMake([model.unitLatitude floatValue], [model.unitLongitude floatValue]));
                    CLLocationDistance distance = BMKMetersBetweenMapPoints(point1, point2);
                    model.distance = [NSString stringWithFormat:@"%.2lf米",distance];
                    [self.bottomlistArray addObject:model];
                }
            }
            
        }
        [self.bottomlistArray sortUsingComparator:^NSComparisonResult(id  _Nonnull obj1, id  _Nonnull obj2) {
            LKMapPointModel *model1 = obj1;
            LKMapPointModel *model2 = obj2;
            if ([model1.unitType isEqual:@"1"] && [model2.unitType isEqual:@"1"]) {
                if ([model1.alarmStatus integerValue] < [model2.alarmStatus integerValue]) {
                    return NSOrderedAscending;
                }else if ([model1.alarmStatus integerValue] > [model2.alarmStatus integerValue]){
                    return NSOrderedDescending;
                }else{
                    return NSOrderedSame;
                }
            }else{
                if ([model1.distance integerValue] < [model2.distance integerValue]) {
                    return NSOrderedAscending;
                }else if ([model1.distance integerValue] > [model2.distance integerValue]){
                    return NSOrderedDescending;
                }else{
                    return NSOrderedSame;
                }
            }
            
        }];
        if (arra.count < [limit integerValue]) {
            [self.tableView.mj_footer endRefreshingWithNoMoreData];
        }
        if (self.bottomlistArray.count == 0) {
            self.tableView.mj_footer.hidden = YES;
        }
        [self.tableView reloadData];
    } failure:^(NSString * _Nullable errorMessage) {
        
    }];
    
}

#pragma tabelview的代理方法

-(NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section{
    return self.bottomlistArray.count;
}
-(UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath{
    LKMapBottomListCell *cell = [tableView dequeueReusableCellWithIdentifier:@"LKMapBottomListCell"];
    cell.model = self.bottomlistArray[indexPath.row];
    cell.caculateTime = self.caculationTimeArray[indexPath.row];
    return cell;
}
-(CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath{
    return 80;
}
-(UIView *)tableView:(UITableView *)tableView viewForHeaderInSection:(NSInteger)section{
    UIView *headerView = [[UIView alloc] init];
    return headerView;
}
-(UIView *)tableView:(UITableView *)tableView viewForFooterInSection:(NSInteger)section{
    return [[UIView alloc] init];
}
-(CGFloat)tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section{
    return section == 0 ? 0.0f : 0.0f;
}
-(CGFloat)tableView:(UITableView *)tableView heightForFooterInSection:(NSInteger)section{
    return 0.0f;
}
-(void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath{
    WS(weakSelf)
    LKMapPointModel *mapPointModel = self.bottomlistArray[indexPath.row];
    CLLocationCoordinate2D selectPt =CLLocationCoordinate2DMake([mapPointModel.unitLatitude doubleValue], [mapPointModel.unitLongitude doubleValue]);
    if ([mapPointModel.unitType isEqual:@"1"]) {
        NSDictionary *param = @{@"code":@"cover",@"roleId":[LKUserInforTool account].roleId};
        [[LKNetDataManager defaultManager] sendRequestMethod:HTTPMethodPOST serverUrl:ServerUrl apiPath:@"/role/server/app/queryAppPermissionsCode" parameters:param progress:^(NSProgress * _Nullable progress) {
            
        } success:^(BOOL isSuccess, id  _Nullable responseObject) {
            if ([responseObject[@"code"] isEqual:@"0000"]) {
                NSString *alertStr;
                if ([mapPointModel.alarmStatus isEqual:@"0"]) {
                    alertStr = @"是否标记为处理中";
                }else if ([mapPointModel.alarmStatus isEqual:@"1"]){
                    alertStr = @"是否标记为已处理";
                }else{
                    return ;
                }
                
                UIAlertController *alertVc = [UIAlertController alertControllerWithTitle:@"友情提示" message:[NSString stringWithFormat:@"%@%@",@"是否标记为",alertStr] preferredStyle:UIAlertControllerStyleAlert];
                [alertVc addAction:[UIAlertAction actionWithTitle:@"取消" style:UIAlertActionStyleCancel handler:^(UIAlertAction * _Nonnull action) {
                    
                }]];
                [alertVc addAction:[UIAlertAction actionWithTitle:@"确定" style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {
                    NSDictionary *param;
                    if ([mapPointModel.alarmStatus isEqual:@"0"]) {
                        param = [NSDictionary dictionaryWithObjectsAndKeys:mapPointModel.Id,@"id",@"1",@"alarmStatus", nil];
                    }else if ([mapPointModel.alarmStatus isEqual:@"1"]){
                        param = [NSDictionary dictionaryWithObjectsAndKeys:mapPointModel.Id,@"id",@"2",@"alarmStatus", nil];
                    }else{
                        return ;
                    }
                    [[LKNetDataManager defaultManager] sendRequestMethod:HTTPMethodPOST serverUrl:ServerUrl apiPath:@"/coverAlarm/server/app/dealAlarmStatus" parameters:param progress:^(NSProgress * _Nullable progress) {
                        
                    } success:^(BOOL isSuccess, id  _Nullable responseObject) {
                        if ([responseObject[@"code"] isEqual:@"0000"]) {
                            [SVProgressHUD showInfoWithStatus:@"处理成功"];
                            [weakSelf headerReloadData];
                            //
                        }else{
                            [SVProgressHUD showInfoWithStatus:responseObject[@"msg"]];
                        }
                    } failure:^(NSString * _Nullable errorMessage) {
                        
                    }];

                }]];
                [self presentViewController:alertVc animated:YES completion:nil];
            }else{
                [SVProgressHUD showInfoWithStatus:responseObject[@"msg"]];
            }
        } failure:^(NSString * _Nullable errorMessage) {
            
        }];

    }
    if ([mapPointModel.unitType isEqual:@"3"]) {
        NSDictionary *param = @{@"code":@"video",@"roleId":[LKUserInforTool account].roleId};
        [[LKNetDataManager defaultManager] sendRequestMethod:HTTPMethodPOST serverUrl:ServerUrl apiPath:@"/role/server/app/queryAppPermissionsCode" parameters:param progress:^(NSProgress * _Nullable progress) {
            
        } success:^(BOOL isSuccess, id  _Nullable responseObject) {
            if ([responseObject[@"code"] isEqual:@"0000"]) {
                [self testVideoPlayWithFatherView:self.playerView WithUrl:mapPointModel.playAddr];
                [self.mediaPlayerView.mediaControl playControl];
            }else{
                [SVProgressHUD showInfoWithStatus:responseObject[@"msg"]];
            }
        } failure:^(NSString * _Nullable errorMessage) {
            
        }];
    }
    if ([mapPointModel.unitType isEqual:@"4"]) {
        LKMapViewController *mapVc = [[LKMapViewController alloc] init];
        mapVc.pt = selectPt;
        mapVc.homeSendModel = mapPointModel;
        mapVc.hidesBottomBarWhenPushed = YES;
        [self.navigationController pushViewController:mapVc animated:YES];
    }
    if ([mapPointModel.unitType isEqual:@"2"]) {
        LKUserInfor *userInfor = [LKUserInforTool account];
        NSDictionary *param = @{@"code":@"guard",@"roleId":[LKUserInforTool account].roleId};
        [[LKNetDataManager defaultManager] sendRequestMethod:HTTPMethodPOST serverUrl:ServerUrl apiPath:@"/role/server/app/queryAppPermissionsCode" parameters:param progress:^(NSProgress * _Nullable progress) {
            
        } success:^(BOOL isSuccess, id  _Nullable responseObject) {
            if ([responseObject[@"code"] isEqual:@"0000"]) {
                if ([mapPointModel.doorStatus isEqual:@"2"]) {
                    UIAlertController *alertVc = [UIAlertController alertControllerWithTitle:@"友情提示" message:@"确定要开锁吗?" preferredStyle:UIAlertControllerStyleAlert];
                    [alertVc addAction:[UIAlertAction actionWithTitle:@"取消" style:UIAlertActionStyleCancel handler:^(UIAlertAction * _Nonnull action) {
                        
                    }]];
                    [alertVc addAction:[UIAlertAction actionWithTitle:@"确定" style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {
                        NSDictionary *param = @{@"command":@"2",@"userUuid":userInfor.userUuid,@"doorUuid":mapPointModel.doorUuid};
                        [[LKNetDataManager defaultManager] sendRequestMethod:HTTPMethodPOST serverUrl:ServerUrl apiPath:@"/unitInfo/server/app/synControl" parameters:param progress:^(NSProgress * _Nullable progress) {
                            
                        } success:^(BOOL isSuccess, id  _Nullable responseObject) {
                            if ([responseObject[@"code"] isEqual:@"0000"]){
                                [SVProgressHUD showInfoWithStatus:@"开门成功"];
                            }else{
                                [SVProgressHUD showInfoWithStatus:responseObject[@"msg"]];
                            }
                        } failure:^(NSString * _Nullable errorMessage) {
                            
                        }];
                    }]];
                    [self presentViewController:alertVc animated:YES completion:nil];
                }else{
                    UIAlertController *alertVc = [UIAlertController alertControllerWithTitle:@"友情提示" message:@"确定要关锁吗?" preferredStyle:UIAlertControllerStyleAlert];
                    [alertVc addAction:[UIAlertAction actionWithTitle:@"取消" style:UIAlertActionStyleCancel handler:^(UIAlertAction * _Nonnull action) {
                        
                    }]];
                    [alertVc addAction:[UIAlertAction actionWithTitle:@"确定" style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {
                        NSDictionary *param = @{@"command":@"1",@"userUuid":userInfor.userUuid,@"doorUuid":mapPointModel.doorUuid};
                        [[LKNetDataManager defaultManager] sendRequestMethod:HTTPMethodPOST serverUrl:ServerUrl apiPath:@"/unitInfo/server/app/synControl" parameters:param progress:^(NSProgress * _Nullable progress) {
                            
                        } success:^(BOOL isSuccess, id  _Nullable responseObject) {
                            if ([responseObject[@"code"] isEqual:@"0000"]){
                                [SVProgressHUD showInfoWithStatus:@"关门成功"];
                            }else{
                                [SVProgressHUD showInfoWithStatus:responseObject[@"msg"]];
                            }
                        } failure:^(NSString * _Nullable errorMessage) {
                            
                        }];
                    }]];
                    [self presentViewController:alertVc animated:YES completion:nil];
                }
            }else{
                [SVProgressHUD showInfoWithStatus:responseObject[@"msg"]];
            }
        } failure:^(NSString * _Nullable errorMessage) {
            
        }];

    }

}
-(NSMutableArray *)bottomlistArray{
    if (!_bottomlistArray) {
        _bottomlistArray = [[NSMutableArray alloc] init];
    }
    return _bottomlistArray;
}


/**
 设置播放源的初始化

 @param fatherView 背景view
 */
-(void)testVideoPlayWithFatherView:(UIView *)fatherView WithUrl:(NSString *)url{
//    self.playerView = [[UIView alloc] initWithFrame:CGRectMake(0, NAVIGATION_BAR_HEIGHT, YWSCREEN_WIDTH, YWMinPlayerHeight)];
//    self.playerView.backgroundColor = [UIColor lightGrayColor];
//    [fatherView addSubview:self.playerView];
    self.mediaPlayerView = [[YWMediaPlayerView alloc] init];
    
//    [_mediaPlayerView playerViewWithUrl:@"rtmp://hzrtmp01.ys7.com:1935/livestream/624520592_1_1_1_0" WithTitle:@"" WithView:_playerView  WithDelegate:self];
    [_mediaPlayerView playerViewWithUrl:url WithTitle:@"" WithView:_playerView  WithDelegate:self];
//    [_mediaPlayerView playerViewWithUrl:@"" WithTitle:@"" WithView:_playerView  WithDelegate:self];
    _mediaPlayerView.mediaControl.totalDurationLabel.hidden = YES;
    _mediaPlayerView.mediaControl.mediaProgressSlider.hidden = YES;
    _mediaPlayerView.mediaControl.currentTimeLabel.hidden = YES;
    _mediaPlayerView.delegate = self;
    __weak typeof(self) weakSelf = self;
//    [self.view addSubview:self.segmentControl];
//    self.segmentControl.selectedSegmentIndex = 0;
//    self.segmentControl.layer.borderColor = [UIColor lightGrayColor].CGColor;
//    self.segmentControl.layer.borderWidth = 0.0000f;
//    [self.segmentControl setTintColor:[UIColor lightGrayColor]];
//    [self.segmentControl setDividerImage:[UIImage imageNamed:@""] forLeftSegmentState:UIControlStateNormal rightSegmentState:UIControlStateNormal barMetrics:UIBarMetricsDefault];
//    [self.segmentControl mas_makeConstraints:^(MASConstraintMaker *make) {
//        make.left.equalTo(self.view.mas_left).offset(0);
//        make.top.equalTo(self.mediaPlayerView.mas_bottom).offset(5);
//        make.height.mas_equalTo(50);
//        make.right.equalTo(self.view.mas_right).offset(0);
//    }];
    dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(0.2 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
//         自动播放
        [weakSelf.mediaPlayerView.mediaControl playControl];
        [weakSelf.mediaPlayerView.mediaControl playControl];
    });
}
/// 改变View大小布局
- (void)viewWillTransitionToSize:(CGSize)size withTransitionCoordinator:(id<UIViewControllerTransitionCoordinator>)coordinator {
    
    if ([UIDevice currentDevice].orientation == UIDeviceOrientationLandscapeLeft ||
        [UIDevice currentDevice].orientation == UIDeviceOrientationLandscapeRight) {
        UIWindow *window = [UIApplication sharedApplication].keyWindow;
        _mediaPlayerView.frame = CGRectMake(0, 0, size.width,size.height);
        _mediaPlayerView.player.view.frame = CGRectMake(0, 0, size.width,size.height);
        _mediaPlayerView.mediaControl.fullScreenBtn.selected = YES;
        _mediaPlayerView.isFullScreen = YES;
        [window addSubview:_mediaPlayerView];
    } else {
        _mediaPlayerView.frame = CGRectMake(0, 0, size.width, size.width/16*9);
        _mediaPlayerView.player.view.frame = CGRectMake(0, 0, size.width, size.width/16*9);
        _mediaPlayerView.mediaControl.fullScreenBtn.selected = NO;
        _mediaPlayerView.isFullScreen = NO;
        [_playerView addSubview:_mediaPlayerView];
    }}
/// 点击关闭按钮
- (void)playerViewClosed:(YWMediaPlayerView *)player {
    
    NSNumber *value = [NSNumber numberWithInt:UIInterfaceOrientationPortrait];
    [[UIDevice currentDevice] setValue:value forKey:@"orientation"];
    [self showHouse];
}

/// 全屏/非全屏切换
- (void)playerView:(YWMediaPlayerView *)player fullscreen:(BOOL)fullscreen {
    
    if (fullscreen == YES) {
        NSNumber *value = [NSNumber numberWithInt:UIInterfaceOrientationLandscapeRight];
        [[UIDevice currentDevice] setValue:value forKey:@"orientation"];
    } else {
        NSNumber *value = [NSNumber numberWithInt:UIInterfaceOrientationPortrait];
        [[UIDevice currentDevice] setValue:value forKey:@"orientation"];
    }
    [self showHouse];
}

/// 播放失败
- (void)playerViewFailePlay:(YWMediaPlayerView *)player {
    NSLog(@"播放失败");
}


/// 准备播放
- (BOOL)playerViewWillBeginPlay:(YWMediaPlayerView *)player {
    NSLog(@"准备播放");
    return YES;
}



/**
 根据选择的不同类型获取不同的数据并刷新展示

 @param seg seg
 */
-(void)chooseDiffrentType:(UISegmentedControl *)seg{
    self.PageIndex = 1;
    self.selectedSeg = seg.selectedSegmentIndex;
    NSString *url;
    if (self.regionId) {
//        url = @"/unitInfo/server/app/selectByReginId";
        url = @"/unitInfo/server/app/getUnitInfoByRoleId";
    }else{
        url = @"/unitInfo/server/app/getUnitInfoByRoleId";
    }
    [self getDataListWithRegionId:self.regionId WithUrl:url WithType:self.selectedSeg];

}

#pragma mark - UISearchBarDelegate

- (BOOL)searchBarShouldBeginEditing:(UISearchBar *)searchBar{
    return YES;
}

- (void)searchBarTextDidBeginEditing:(UISearchBar *)searchBar {
    searchBar.showsCancelButton = YES;
    
}
- (void)searchBarSearchButtonClicked:(UISearchBar *)searchBar
{
    NSLog(@"SearchButton");
    self.unitAddr = searchBar.text;
    self.regionId = nil;
    [_localBtn setTitle:@"上海市" forState:UIControlStateNormal];
    _localBtn.size = [NSString sizeWidthWidth:@"上海市" font:[UIFont systemFontOfSize:12] maxHeight:NAVIGATION_BAR_HEIGHT - STATUS_BAR_HEIGHT];
    [searchBar resignFirstResponder];
    searchBar.showsCancelButton = NO;
    self.PageIndex = 1;
    [self getDataListWithRegionId:self.regionId WithUrl:@"/unitInfo/server/app/getUnitInfoByRoleId" WithType:self.selectedSeg];
}
- (void)searchBarCancelButtonClicked:(UISearchBar *)searchBar
{
    searchBar.showsCancelButton = NO;
    searchBar.text = @"";
    self.unitAddr = searchBar.text;
    UIButton *cancelBtn = [searchBar valueForKey:@"cancelButton"]; //首先取出cancelBtn
    cancelBtn.enabled = YES; //把enabled设置为yes
    [searchBar resignFirstResponder];
    self.PageIndex = 1;
    [self getDataListWithRegionId:self.regionId WithUrl:@"/unitInfo/server/app/getUnitInfoByRoleId" WithType:self.selectedSeg];
    
}
-(void)viewDidDisappear:(BOOL)animated{
    [super viewDidDisappear:animated];
    
}
- (void)searchBar:(UISearchBar *)searchBar textDidChange:(NSString *)searchText
{
    
}
/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

@end
